"""
Copyright (c) 2022 Huawei Technologies Co.,Ltd.

openGauss is licensed under Mulan PSL v2.
You can use this software according to the terms and conditions of the Mulan PSL v2.
You may obtain a copy of Mulan PSL v2 at:

          http://license.coscl.org.cn/MulanPSL2

THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
See the Mulan PSL v2 for more details.
"""
"""
Case Type   : 故障&可靠性测试
Case Name   : 数据库连接数大于全局连接数
Create At   : 2021/10/08
@zou_jialiang0505328126
Description :
    1.配置max_connections=20
    2.重启数据库生效
    3.创建数据库，最大连接数为21
    4.创建普通用户
    5.使用普通用户连接数据库，创建21个session
Expect      :
    1.配置成功
    2.重启成功
    3.创建数据库成功
    4.创建用户成功
    5.前20个连接正常，第21个连接报错
History     :
"""

import unittest
import time
from yat.test import Node
from yat.test import macro
from testcase.utils.Common import Common
from testcase.utils.Constant import Constant
from testcase.utils.CommonSH import CommonSH
from testcase.utils.CommonSH import RestartDbCluster
from testcase.utils.Logger import Logger
from testcase.utils.ComThread import ComThread


class CPUOverloadAndRunTPCC(unittest.TestCase):
    nodes_tuple = ('PrimaryDbUser', 'Standby1DbUser', 'Standby2DbUser')

    @RestartDbCluster(*nodes_tuple)
    def setUp(self):
        self.log = Logger()
        self.log.info(
            '---------Opengauss_Reliability_Db_System_Case231:开始执行---------')
        self.primary_root_node = Node(node='PrimaryRoot')
        self.primary_user_node = Node(node='PrimaryDbUser')
        self.com = Common()
        self.primary_sh = CommonSH('PrimaryDbUser')
        self.db_name = "d_db_system_case231"
        self.user_name = "u_db_system_case231"
        self.constant = Constant()
        result = self.primary_sh.executDbSql('show max_connections;')
        self.log.info(f"max_connections is {result}")
        self.max_connections = result.strip().splitlines()[-2]

    def test_main(self):
        text = '----step1: 配置max_connections=20 expect:成功----'
        self.log.info(text)
        result = self.primary_sh.executeGsguc('set',
                                              self.constant.GSGUC_SUCCESS_MSG,
                                              "max_connections=20")
        self.assertTrue(result, '执行失败:' + text)

        text = '----step2: 重启数据库生效 expect:成功----'
        self.log.info(text)
        result = self.primary_sh.stopDbCluster()
        self.assertTrue(result, '执行失败:' + text)
        result = self.primary_sh.startDbCluster()
        self.assertTrue(result, '执行失败:' + text)

        text = '----step3: 创建数据库，最大连接数为21 expect:成功----'
        self.log.info(text)
        sql = f"create database {self.db_name} with LC_COLLATE='zh_CN.gbk' " \
            f"LC_CTYPE = 'zh_CN.gbk' CONNECTION LIMIT=21;"
        result = self.primary_sh.executDbSql(sql)
        self.log.info(result)
        self.assertIn(self.constant.CREATE_DATABASE_SUCCESS_MSG, result,
                      '执行失败:' + text)

        text = '----step4: 创建普通用户 expect:成功----'
        self.log.info(text)
        sql = f"create user {self.user_name} with password " \
            f"'{macro.PASSWD_INITIAL}';"
        result = self.primary_sh.executDbSql(sql)
        self.log.info(result)
        self.assertIn(self.constant.CREATE_ROLE, result, '执行失败:' + text)

        text = '----step5: 使用普通用户连接数据库，创建21个session ' \
               'expect:前20个连接正常，第21个连接报错----'
        self.log.info(text)
        connect_thread = []
        for i in range(21):
            connect_thread.append(ComThread(
                self.primary_sh.executDbSql, args=(
                    'select pg_sleep(240);', self.db_name,
                    f'-U {self.user_name} -W {macro.PASSWD_INITIAL}')))
            connect_thread[i].setDaemon(True)
            connect_thread[i].start()
            time.sleep(5)
        for i in range(21):
            connect_thread[i].join(400)
            result = connect_thread[i].get_result()
            self.log.info(result)
            if 20 == i:
                self.assertIn('Too many', result)
            else:
                self.assertNotIn('Too many', result)
        time.sleep(5)


    def tearDown(self):
        self.log.info("----------还原集群配置--------------")
        self.primary_sh.executeGsguc('set',
                                     self.constant.GSGUC_SUCCESS_MSG,
                                    f"max_connections={self.max_connections}")
        self.primary_sh.stopDbCluster()
        self.primary_sh.startDbCluster()
        self.log.info("------------------删除表-----------------")
        sql = f"drop database if exists {self.db_name};" \
            f"drop user if exists {self.user_name} cascade;"
        result = self.primary_sh.executDbSql(sql)
        self.log.info(result)
        self.log.info(
            '--------Opengauss_Reliability_Db_System_Case231:执行完成--------')
